<?php
namespace App\Services\Activity;

use App\Models\MainDB\AccountLog;
use App\Models\MainDB\Coin;
use App\Models\MainDB\Gift;
use App\Models\MainDB\GiftBackpack;
use App\Models\MainDB\MallOrders;
use App\Models\MainDB\MallProducts;
use App\Models\MainDB\User;
use Illuminate\Database\Eloquent\Collection;

class RewardService
{

    public function add(Collection $rewards, int $uid, string $changeDesc = '', int $changeType = 0): Collection
    {
        // 礼物
        $rewards->where('reward_type', Gift::RELATION_TYPE)->each(function ($item) use ($uid) {

            $item->reward = $item->gift;
            if (! empty($item->reward)) {
                (new GiftBackpack())->addGift($uid, $item->reward->id, $item->count);
            }
            return $item;
        });

        // 商品
        $rewards->where('reward_type', MallProducts::RELATION_TYPE)->each(function ($item) use ($uid) {
            $item->reward = $item->product;
            if (! empty($item->reward)) {
                (new MallOrders())->addProduct($uid, $item->reward->id, $item->count, $item->reward->category_id);
            }
            return $item;
        });

        // 金币
        $totalCoin = $rewards->where('reward_type', Coin::RELATION_TYPE)->sum('count');

        if ($totalCoin > 0) {
            User::query()->where('user_id', $uid)->increment('money', $totalCoin);
            AccountLog::query()->create([
                'user_id'     => $uid,
                'user_money'  => $totalCoin,
                'change_time' => time(),
                'change_desc' => $changeDesc,
                'change_type' => $changeType,
            ]);
        }

        return $rewards;
    }


}
